package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.FromSearchListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.from.ChangeShiftsBean;
import com.glory.hikvisionmobile.bean.from.DrugAddBean;
import com.glory.hikvisionmobile.bean.from.FormsBean;
import com.glory.hikvisionmobile.bean.from.FromSearchBean;
import com.glory.hikvisionmobile.bean.from.IQPCRecordBean;
import com.glory.hikvisionmobile.bean.from.LocationBean;
import com.glory.hikvisionmobile.bean.from.LocationListBean;
import com.glory.hikvisionmobile.bean.from.MaterielRecordBean;
import com.glory.hikvisionmobile.bean.from.ReplaceRecordBean;
import com.glory.hikvisionmobile.bean.from.UserBean;
import com.glory.hikvisionmobile.bean.from.UserListBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.EditTextEnterUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class From_FromSearchActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.tvFromType)
    TextView tvFromType;
    @BindView(R.id.ivFromTypeListArrow)
    ImageView ivFromTypeListArrow;
    @BindView(R.id.flFromTypeList)
    FrameLayout flFromTypeList;
    @BindView(R.id.tvBeginTime)
    TextView tvBeginTime;
    @BindView(R.id.ivBeginTimeArrow)
    ImageView ivBeginTimeArrow;
    @BindView(R.id.flBeginTimeList)
    FrameLayout flBeginTimeList;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.ivEndTimeArrow)
    ImageView ivEndTimeArrow;
    @BindView(R.id.flEndTimeList)
    FrameLayout flEndTimeList;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.rvFromSearchList)
    RecyclerView rvFromSearchList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.etMaterialName)
    FreeUI_ClearEditText etMaterialName;
    @BindView(R.id.llEqpLayout)
    LinearLayout llEqpLayout;
    @BindView(R.id.llMaterielLayout)
    LinearLayout llMaterielLayout;
    @BindView(R.id.llChangeShiftLayout)
    LinearLayout llChangeShiftLayout;
    @BindView(R.id.flRegionList)
    FrameLayout flRegionList;
    @BindView(R.id.tvRegion)
    TextView tvRegion;
    @BindView(R.id.ivRegionListArrow)
    ImageView ivRegionListArrow;
    @BindView(R.id.flChangeUserList)
    FrameLayout flChangeUserList;
    @BindView(R.id.tvChangeUser)
    TextView tvChangeUser;
    @BindView(R.id.ivChangeUserListArrow)
    ImageView ivChangeUserListArrow;
    @BindView(R.id.cbMySelf)
    CheckBox cbMySelf;


    private FreeUI_GeneralPop fromPop;
    private CustomDatePicker mDatePicker;
    private String beginDate;
    private String endDate;
    boolean isBegin;
    private FromSearchListAdapter fromSearchListAdapter;
    private FormsBean formsBean;
    private List<String> locationList = new ArrayList<>();
    private FreeUI_GeneralPop locationPop;
    private FreeUI_GeneralPop userPop;
    private String location;
    private List<String> userList = new ArrayList<>();


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_from_from_search;
    }

    @Override
    protected void initView() {
        initDatePicker();
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv1.setText("表单类型");
        listTv2.setText("时间");

        rvFromSearchList.setLayoutManager(new LinearLayoutManager(From_FromSearchActivity.this));
        rvFromSearchList.setItemAnimator(new DefaultItemAnimator());
        rvFromSearchList.addItemDecoration(new DividerItemDecoration(From_FromSearchActivity.this, 1));
        fromSearchListAdapter = new FromSearchListAdapter(null);
        fromSearchListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        fromSearchListAdapter.isFirstOnly(true);
        rvFromSearchList.setAdapter(fromSearchListAdapter);

        fromSearchListAdapter.setOnItemClickListener(this);

        EditTextEnterUtils.initEnterToUpperCase(etEqpWork);

        cbMySelf.setText(Constant.LOGIN_BEAN.getDescription());

    }

    @Override
    protected void initData() {
        NetUtils.requestDara("HIK.PdaBaseLocation", this, null, new FreeUI_DialogEntityCallBack<BaseResponseBean<LocationListBean>>
                (new TypeToken<BaseResponseBean<LocationListBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LocationListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    locationList.clear();
                    locationList.add(0,"");
                    List<LocationBean> locationBeans = response.body().getBody().getxPdaLocations();
                    for (LocationBean bean : locationBeans) {
                        locationList.add(bean.getName() + "/" + bean.getDescription());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LocationListBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaBaseLocation");
            }
        });
    }

    private void initDatePicker() {
        long beginTimestamp = FreeApi_DateUtils.str2Long("1992-03-20", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            if (isBegin) {
                beginDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvBeginTime.setText(beginDate);
            } else {
                endDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvEndTime.setText(endDate);
            }

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

    private List<String> getFromList() {
        List<String> fromList = new ArrayList<>();
        fromList.add("药液添加记录表");
        fromList.add("物料领用退还记录表");
        fromList.add("品质检验记录表");
        fromList.add("交接班记录表");
        fromList.add("易损件更换记录");
        return fromList;

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("表单查询");
//        NewBuild
        freeUI_titleView.setRightListener("新建", v -> {

            initPermission("NewBuild", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    startActivity(tvFromType.getText().toString().trim(), false, 0);
                }
            });



        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!FreeApi_StringUtils.isEmpty(beginDate) && !FreeApi_StringUtils.isEmpty(endDate)) {
            search();
        }
    }

    @OnClick({R.id.flFromTypeList, R.id.flBeginTimeList, R.id.flEndTimeList, R.id.tvSearch,R.id.flRegionList,R.id.flChangeUserList,R.id.cbMySelf})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flFromTypeList:
                if (fromPop != null) {
                    if (fromPop.isShowing()) {
                        fromPop.dismiss();
                    }
                } else {
                    fromPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flFromTypeList.getWidth(), getFromList(), ivFromTypeListArrow, (code, i) -> {

                        if (code.equals("物料领用退还记录表")) {     //独立出去查询
                            boolean newBuild = !actionControl("NewBuild");
                            boolean search = !actionControl("Search");
                            Log.i("test", newBuild + "/" + search);
                            Bundle bundle = new Bundle();
                            bundle.putBoolean("NewBuild", newBuild);
                            bundle.putBoolean("Search", search);
                            FreeApi_Utils.skipWithExtraIntent("header", bundle, From_FromSearchActivity.this, From_MaterielSearchActivity.class);
                            return;
                        }

                        tvFromType.setText(code);
                        etEqpWork.setText("");
                        etMaterialName.setText("");
                        llEqpLayout.setVisibility(code.equals("易损件更换记录") ? View.VISIBLE : View.GONE);
                        llChangeShiftLayout.setVisibility(code.equals("交接班记录表") ? View.VISIBLE : View.GONE);
                        if (code.equals("易损件更换记录") | code.equals("物料领用退还记录表")){
                            llMaterielLayout.setVisibility(View.VISIBLE);
                        }else {
                            llMaterielLayout.setVisibility(View.GONE);
                        }
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivFromTypeListArrow);
                fromPop.showAsDropDown(flFromTypeList, 0, 0);
                break;
            case R.id.flBeginTimeList:
                isBegin = true;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flEndTimeList:
                isBegin = false;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.cbMySelf:
                if (cbMySelf.isChecked()) {
                    flChangeUserList.setEnabled(false);
                    tvChangeUser.setText("");
                }else {
                    flChangeUserList.setEnabled(true);
                }
                break;
            case R.id.flRegionList:
                if (locationList.size() <= 0) {
                    showToast("未获取到区域列表", false);
                    return;
                }

                if (locationPop != null) {
                    if (locationPop.isShowing()) {
                        locationPop.dismiss();
                    }
                } else {
                    locationPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flRegionList.getWidth(), locationList, ivRegionListArrow, (code, i) -> {
                        tvRegion.setText(code);
                        location = code.split("/")[0];
                        //根据区域查用户
                        tvChangeUser.setText("");
                        userPop = null;
                        JsonObject map = new JsonObject();
                        map.addProperty("phone2", location);
                        map.addProperty("department", "");
                        NetUtils.requestDara("HIK.PdaADUserQuery", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<UserListBean>>
                                (new TypeToken<BaseResponseBean<UserListBean>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<UserListBean>> response) {
                                super.onSuccess(response);
                                userList.clear();
                                userList.add(0,"");
                                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                                    List<UserBean> userBeans = response.body().getBody().getxPdaADUsers();
                                    for (UserBean bean : userBeans){
                                        userList.add(bean.getDescription());
                                    }
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<UserListBean>> response) {
                                super.onError(response);
                                loadError(response.getException(), "HIK.PdaADUserQuery");
                            }
                        });
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivRegionListArrow);
                locationPop.showAsDropDown(flRegionList, 0, 0);
                break;
            case R.id.flChangeUserList:
                if (userList.size() <= 0) {
                    showToast("未获取到被交接人列表", false);
                    return;
                }

                if (userPop != null) {
                    if (userPop.isShowing()) {
                        userPop.dismiss();
                    }
                } else {

                    userPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flChangeUserList.getWidth(), userList, ivChangeUserListArrow, (code, i) -> {
                        tvChangeUser.setText(code);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivChangeUserListArrow);
                userPop.showAsDropDown(flChangeUserList, 0, 0);
                break;
            case R.id.tvSearch:

                initPermission("Search", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        if (!FreeApi_StringUtils.isEmpty(beginDate) && !FreeApi_StringUtils.isEmpty(endDate)) {
                            int i = FreeApi_DateUtils.compare_date(endDate, beginDate, "yyyy-MM-dd");
                            if (i != 1) {
                                showToast("结束日期不能大于开始日期", false);
                                tvBeginTime.setText("请选择开始日期");
                                tvEndTime.setText("请选择结束日期");
                                beginDate = "";
                                endDate = "";
                                return;
                            }
                            search();
                        } else {
                            showToast("开始时间和结束时间不能为空", false);
                        }
                    }
                });
                break;
        }
    }

    private void search() {
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "query");
        map.addProperty("formType", getFromType());
        map.addProperty("fromTime", beginDate);
        map.addProperty("toTime", endDate);
        map.addProperty("eqpId",etEqpWork.getText().toString().trim());
        map.addProperty("materialName",etMaterialName.getText().toString().trim());
        map.addProperty("area",location);
        map.addProperty("handover",cbMySelf.isChecked() ? Constant.LOGIN_BEAN.getDescription() : tvChangeUser.getText().toString().trim());
        NetUtils.requestDara("HIK.PdaForm", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<FromSearchBean>>
                (new TypeToken<BaseResponseBean<FromSearchBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<FromSearchBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    formsBean = response.body().getBody().getxPdaForms();
                    getFromType(formsBean);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<FromSearchBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaForm");
            }
        });
    }

    private String getFromType() {
        StringBuffer type = new StringBuffer();
        switch (tvFromType.getText().toString().trim()) {
            case "药液添加记录表":
                type.append("YY");
                break;
            case "物料领用退还记录表":
                type.append("WLLT");
                break;
            case "品质检验记录表":
                type.append("IPQC");
                break;
            case "交接班记录表":
                type.append("JJB");
                break;
            case "易损件更换记录":
                type.append("YSPJ");
                break;
            default:
                break;
        }
        return type.toString();
    }

    private void getFromType(FormsBean formsBean) {
        List<String> timeList = new ArrayList<>();
        switch (tvFromType.getText().toString().trim()) {
            case "药液添加记录表":
                List<DrugAddBean> drugAddBeans = formsBean.getxPdaFormYaoYes();
                for (DrugAddBean data : drugAddBeans) {
                    timeList.add(data.getCreated());
                }
                fromSearchListAdapter.setFromType("药液添加记录表");
                fromSearchListAdapter.setNewData(timeList);
                break;
            case "物料领用退还记录表":
                List<MaterielRecordBean> materielRecordBeans = formsBean.getxPdaFormMatLingTuis();
                for (MaterielRecordBean data : materielRecordBeans) {
                    timeList.add(data.getCreated());
                }
                fromSearchListAdapter.setFromType("物料领用退还记录表");
                fromSearchListAdapter.setNewData(timeList);
                break;
            case "品质检验记录表":
                List<IQPCRecordBean> iqpcRecordBeans = formsBean.getxPdaFormIpQcs();
                for (IQPCRecordBean data : iqpcRecordBeans) {
                    timeList.add(data.getCreated());
                }
                fromSearchListAdapter.setFromType("品质检验记录表");
                fromSearchListAdapter.setNewData(timeList);
                break;
            case "交接班记录表":
                List<ChangeShiftsBean> changeShiftsBeans = formsBean.getxPdaFormJiaoJieBans();
                for (ChangeShiftsBean data : changeShiftsBeans) {
                    timeList.add(data.getCreated());
                }
                fromSearchListAdapter.setFromType("交接班记录表");
                fromSearchListAdapter.setNewData(timeList);
                break;
            case "易损件更换记录":
                List<ReplaceRecordBean> replaceRecordBeans = formsBean.getxPdaFormYiSunPeiJians();
                for (ReplaceRecordBean data : replaceRecordBeans) {
                    timeList.add(data.getCreated());
                }
                fromSearchListAdapter.setFromType("易损件更换记录");
                fromSearchListAdapter.setNewData(timeList);
                break;
            default:
                break;
        }

    }

    private void startActivity(String type, boolean input, @Nullable int position) {
        switch (type) {
            case "药液添加记录表":
                if (input) {
                    DrugAddBean drugAddBean = formsBean.getxPdaFormYaoYes().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("DrugAddBean", drugAddBean);
                    FreeApi_Utils.skipWithExtraIntent("header", bundle, this, From_AddDrugRecordActivity.class);
                } else {
                    FreeApi_Utils.skipWithExtraIntent("header", this, From_AddDrugRecordActivity.class);
                }
                break;
            case "物料领用退还记录表":
                if (input) {
                    MaterielRecordBean materielRecordBean = formsBean.getxPdaFormMatLingTuis().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("MaterielRecordBean", materielRecordBean);
                    FreeApi_Utils.skipWithExtraIntent("header", bundle, this, From_MaterielRecordActivity.class);
                } else {
                    FreeApi_Utils.skipWithExtraIntent("header", this, From_MaterielRecordActivity.class);
                }
                break;
            case "品质检验记录表":
                if (input) {
                    IQPCRecordBean iqpcRecordBean = formsBean.getxPdaFormIpQcs().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("IQPCRecordBean", iqpcRecordBean);
                    FreeApi_Utils.skipWithExtraIntent("header", bundle, this, From_IQPCRecordActivity.class);
                } else {
                    FreeApi_Utils.skipWithExtraIntent("header", this, From_IQPCRecordActivity.class);
                }
                break;
            case "交接班记录表":
                if (input) {
                    ChangeShiftsBean changeShiftsBean = formsBean.getxPdaFormJiaoJieBans().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("ChangeShiftsBean", changeShiftsBean);
                    FreeApi_Utils.skipWithExtraIntent("header", bundle, this, From_ChangeShiftsActivity.class);
                } else {
                    FreeApi_Utils.skipWithExtraIntent("header", this, From_ChangeShiftsActivity.class);
                }
                break;
            case "易损件更换记录":
                if (input) {
                    ReplaceRecordBean replaceRecordBean = formsBean.getxPdaFormYiSunPeiJians().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("ReplaceRecordBean", replaceRecordBean);
                    FreeApi_Utils.skipWithExtraIntent("header", bundle, this, From_ReplaceRecordActivity.class);
                } else {
                    FreeApi_Utils.skipWithExtraIntent("header", this, From_ReplaceRecordActivity.class);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        startActivity(tvFromType.getText().toString().trim(), true, position);
    }
}
